package com.tbit.uqbike.client.service.impl;

import com.tbit.uqbike.client.dao.core.RideCardDao;
import com.tbit.uqbike.client.exception.BaseException;
import com.tbit.uqbike.client.pojo.RideCard;
import com.tbit.uqbike.client.pojo.RideCardUser;
import com.tbit.uqbike.client.service.RideCardService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
import java.util.*;

/**
 * 骑行会员
 *
 * @author Leon
 * 2019年9月24日 下午4:05:36
 */
@Service("rideCardService")
public class RideCardServiceImpl implements RideCardService {

    @Autowired
    private RideCardDao rideCardDao;

    @Override
    public List<RideCard> queryPage(Integer accountId, Integer pageNO, Integer rowCount) {
        Map<String, Object> map = new HashMap<>();
        map.put("accountId", accountId);
        map.put("page", (pageNO - 1) * rowCount);
        map.put("rowCount", rowCount);

        return rideCardDao.queryPage(map);
    }

    @Override
    public Integer queryCount(Integer accountId) {
        Map<String, Object> map = new HashMap<>();
        map.put("accountId", accountId);
        return rideCardDao.queryCount(map);
    }

    @Override
    public RideCard getById(Integer rideCardId) {
        return rideCardDao.getById(rideCardId);
    }

    @Override
    public RideCard getByAccountId(Integer accountId, Integer feeId) {
        Map<String, Object> map = new HashMap<>();
        map.put("accountId", accountId);
        map.put("feeId", feeId);
        return rideCardDao.getByAccountId(map);
    }

    @Override
    public RideCard getByOrderNO(String orderNO) {
        return rideCardDao.getByOrderNO(orderNO);
    }

    //校验骑行卡是否在有效日期和有效周几
    @Override
    public List<RideCardUser> checkValidaDate(List<RideCardUser> rideCardUsers, String rideStartTime){
        String[] split = rideStartTime.split(" ");
        List<RideCardUser> rideCardUsersExclude = new ArrayList<>();
        // 获取骑行时间
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("HH:mm:ss");
        LocalTime now = LocalTime.parse(split[1], formatter);
        //获取当前星期几
        String datestring =split[0];
        SimpleDateFormat dateFormat =  new SimpleDateFormat("yyyy-MM-dd");
        Date date = null;
        try {
            date = dateFormat.parse(datestring);
        } catch (ParseException e) {
            throw new BaseException("-30005", "日期转换错误");
        }
        Calendar calendar =  Calendar.getInstance();
        calendar.setTime(date);
        int day =  calendar.get(Calendar.DAY_OF_WEEK);

        //排除不在有效时间和有效日期的
        for (RideCardUser rideCardUser : rideCardUsers) {
            boolean isInTimeRange = true;
            boolean isNormalWorkday = true;
            RideCard rideCardById = getById(rideCardUser.getRideCardId());
            if (rideCardById == null) {
                continue; // 避免空指针异常
            }
            String vaildTime = rideCardById.getVaildTime();
            String validWeek = rideCardById.getValidWeek();
            // 调用方法检查当前时间是否在给定的时间段内
            if (vaildTime != null && !"".equals(vaildTime)) {
                isInTimeRange = isNowInTimeRanges(now, vaildTime);
            }
            // 调用方法检查当前日期是否在给定的日期段内
            if (validWeek != null && !"".equals(validWeek)) {
                isNormalWorkday = isWorkday(day, validWeek);
            }
            if (isInTimeRange && isNormalWorkday) {
                rideCardUsersExclude.add(rideCardUser);
            }

        }
        return  rideCardUsersExclude;
    }



    /**
     * 判断当前时间是否在给定的时间段列表内。
     * @param timeRanges 时间段字符串，格式为"start-end;start-end"
     * @return 如果当前时间在任何一个时间段内，则返回true，否则返回false。
     */
    public static boolean isNowInTimeRanges(LocalTime now, String timeRanges) {
        List<String> rangeList = Arrays.asList(timeRanges.split(";"));
        for (String range : rangeList) {
            String[] bounds = range.split("-");
            if (bounds.length != 2) {
                throw new BaseException("-30005", "有效日期格式错误");
            }

            LocalTime start = LocalTime.parse(bounds[0], DateTimeFormatter.ofPattern("HH:mm:ss"));
            LocalTime end = LocalTime.parse(bounds[1], DateTimeFormatter.ofPattern("HH:mm:ss"));

            // 检查当前时间是否在范围内
            if (now.isAfter(start) && now.isBefore(end)) {
                return true; // 只要在一个范围内就返回true
            }
        }
        return false; // 遍历完所有范围都没有匹配到，返回false
    }


    /**
     * 检查给定日期是否是正常工作日，基于提供的工作日列表字符串。
     * @param date 要检查的日期
     * @param workingDaysString 工作日列表字符串，格式如 "2,4"（代表星期一和星期三）
     * @return 如果日期是正常工作日，返回true，否则返回false。
     */
    public static boolean isWorkday(int day, String workingDaysString) {
        // 判断今天是否能使用
        return workingDaysString.contains(String.valueOf(day));
    }

    public static void main(String[] args) {
        RideCardUser rideCardUser = new RideCardUser();
        rideCardUser.setRideCardId(100830);
        ArrayList<RideCardUser> rideCardUsers = new ArrayList<RideCardUser>();
        rideCardUsers.add(rideCardUser);
        String rideStartTime = "2024-05-13 13:41:00";
        RideCardServiceImpl rideCardService = new RideCardServiceImpl();
        List<RideCardUser> rideCardUsers1 = rideCardService.checkValidaDate(rideCardUsers, rideStartTime);
    }
}
